package hu.issue.framework.web.servlet;

import hu.issue.framework.web.controller.Inject;

import java.lang.reflect.Field;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

class BeanInjector {
	private static Logger log = Logger.getLogger(BeanInjector.class.getName());

	private final Context context;

	public BeanInjector() throws NamingException {
		this.context = new InitialContext();
	}

	public void inject(final Object bean) throws NamingException, IllegalArgumentException, IllegalAccessException {
		log.info("processing: " + bean);
		final Field[] fields = bean.getClass().getDeclaredFields();
		for (final Field field : fields) {
			final Inject injectAnnotation = field.getAnnotation(Inject.class);
			if (injectAnnotation == null) {
				log.info("Annotation not found on field " + field.getName());
				continue;
			}
			log.info(String.format("Injecting to field %s (type: %s)", field.getName(), field.getType()));
			final String jndiName = String.format("java:global/issue/%sBean", field.getType().getSimpleName());
			try {
				field.setAccessible(true);
				field.set(bean, this.context.lookup(jndiName));
			} finally {
				field.setAccessible(false);
			}
		}
	}
}